#define _CRT_SECURE_NO_WARNINGS 1
class Solution {
public:
    long long maximumTotalDamage(vector<int>& power) {
        int n = power.size();
        sort(power.begin(), power.end());
        vector<pair<int, int>> arr;
        arr.push_back({ power[0], 1 });
        for (int i = 1; i < n; i++) {
            if (power[i] == power[i - 1]) arr[arr.size() - 1].second++;
            else arr.push_back({ power[i], 1 });
        }
        vector<long long> dp(arr.size());
        dp[0] = (long long)arr[0].first * arr[0].second;
        for (int i = 1; i < arr.size(); i++) {
            long long cur = arr[i].first * arr[i].second;
            long long j = i - 1, prev = 0;
            while (j >= 0 && arr[j].first >= arr[i].first - 2) j--;
            if (j != -1) prev = dp[j];
            dp[i] = max(prev + cur, dp[i - 1]);
        }
        //for(int i = 0; i < arr.size(); i++) cout << dp[i] << ' ';
        return dp[arr.size() - 1];
    }
};